package RunService;
import Client.ServerToClient;
import Client.SocketClient;
import Watcher.watchService;




public class MyService 
{

	private static MyService serviceInstance = new MyService();
	private boolean stopped=false;
	private static boolean first;
	private boolean start = false;

	private MyService() {
		super();
		first=true;
		System.out.println("in constructor, first is "+first);
	}
	public static void windowsService(String args[])
	{
		System.out.println("\n first is "+first);
		String cmd="start";
		System.out.println("\n******** "+cmd);
		if(args.length>0)
		{
			cmd=args[0];
		}
		if("start".equals(cmd))
		{

			serviceInstance.start();
		}
		else
		{
			serviceInstance.stop();
		}
	}
	public boolean start()
	{
		System.out.println("in start");
		//		boolean play=watchService.getWsInstance().isPlay();
		if(first)
		{
			first = false;
			SocketClient sc=new SocketClient();
			sc.run();
		}
		System.out.println("in start = "+start);
		if(start)
		{
			return false;
		}
		//else
		//		{
		start = true;
		stopped=false;
		watchService.getWsInstance().setPlay(true);
		ServerToClient.getInstance().setPlay(true);

		//		}
		System.out.println("My service start "+ new java.util.Date());
		while(!stopped)
		{
			System.out.println("My service Executing " + new java.util.Date());
			synchronized (this)
			{
				try 
				{
					this.wait(60000);
				} 
				catch (InterruptedException e) 
				{
					e.printStackTrace();
				}
			}
		}
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("My service finish" + new java.util.Date());
		return true;
	}
	public boolean stop()
	{
		//		boolean play=watchService.getWsInstance().isPlay();
		System.out.println("in stop = "+start);
		if(!start)
		{
			return false;
		}

		//		else
		//		{
		start = false;
		stopped=true;
		watchService.getWsInstance().stopWatch();
		ServerToClient.getInstance().stopTransfer();
		synchronized (this)
		{
			this.notify();
		}

		return true;
		//		}
	}
}
